{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Instruction Power Differences\n",
    "\n",
    "Supported setups:\n",
    "\n",
    "SCOPES:\n",
    "\n",
    "* OPENADC\n",
    "* CWNANO\n",
    "\n",
    "PLATFORMS:\n",
    "\n",
    "* CWLITEARM\n",
    "* CWLITEXMEGA\n",
    "* CWNANO"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This tutorial will introduce you to measuring the power consumption of a device under attack. It will demonstrate how the power consumption of a target changes based on what operations it's doing.\n",
    "\n",
    "If you haven't yet, you should probably complete Tutorial B1, which introduces building firmware, programming the target, and scripting."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "SCOPETYPE = 'OPENADC'\n",
    "PLATFORM = 'CWLITEARM'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Setting up Firmware"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In this tutorial, we will once again be working off of the simpleserial-base firmware.\n",
    "\n",
    "Let's start by creating a new project and building our firmware:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bash\n",
    "cd ../hardware/victims/firmware/\n",
    "mkdir -p simpleserial-base-lab2 && cp -r simpleserial-base/* $_\n",
    "cd simpleserial-base-lab2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "CRYPTO_TARGET = \"NONE\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bash -s \"$PLATFORM\" \"$CRYPTO_TARGET\"\n",
    "cd ../hardware/victims/firmware/simpleserial-base-lab2\n",
    "make PLATFORM=$1 CRYPTO_TARGET=$2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As in the previous tutorial, we'll need to modify our firmware. Navigate to the `get_pt()` function:\n",
    "```C\n",
    "uint8_t get_pt(uint8_t* pt)\n",
    "{\n",
    "\t/**********************************\n",
    "\t* Start user-specific code here. */\n",
    "\ttrigger_high();\n",
    "\t\n",
    "\t//16 hex bytes held in 'pt' were sent\n",
    "\t//from the computer. Store your response\n",
    "\t//back into 'pt', which will send 16 bytes\n",
    "\t//back to computer. Can ignore of course if\n",
    "\t//not needed\n",
    "\t\n",
    "\ttrigger_low();\n",
    "\t/* End user-specific code here. *\n",
    "\t********************************/\n",
    "\tsimpleserial_put('r', 16, pt);\n",
    "\treturn 0x00;\n",
    "}\n",
    "\n",
    "```\n",
    "\n",
    "To start off, we'll add a simple `for` loop. We'll start off by looking at how the power trace changes based on how long the loop is. Start with a loop (make sure your variables are volatile) that runs from 0 to 4:\n",
    "\n",
    "```C\n",
    "for(volatile int i = 0; i < 5; i++);\n",
    "```\n",
    "\n",
    "Next, we'll move on to actually capturing and displaying the power trace."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## ChipWhisperer Setup"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Setup for this tutorial will be pretty similar to Tutorial B1, so we'll skip most of it by calling some helper scripts. This setup should work for most targets, but if you're using a target other than the XMEGA or STM32F3 (CWLite w/ Arm), you may need to call a different script or do additional setup (like programming the target with an external programmer). See the wiki page for your target for more information.\n",
    "\n",
    "If you're curious about what's happening in these helper scripts, they're typically located in the `Helper_Scripts` folder."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bash -s \"$PLATFORM\" \"$CRYPTO_TARGET\"\n",
    "cd ../hardware/victims/firmware/simpleserial-base-lab2\n",
    "make PLATFORM=$1 CRYPTO_TARGET=$2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%run \"Helper_Scripts/Setup_Generic.ipynb\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "By default, the scope will capture many more traces than we need, so we'll reduce that to 1000."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "scope.adc.samples = 1000\n",
    "fw_path = '../hardware/victims/firmware/simpleserial-base-lab2/simpleserial-base-{}.hex'.format(PLATFORM)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Programming is the same as in the last part:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "cw.program_target(scope, prog, fw_path)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Capturing Traces"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(scope)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Like before, most of this should look familiar from the last tutorial. We'll start by programming the target, then capturing a trace, and finally displaying it using bokeh. We don't really care about what the target responds with this time, so we won't do anything with what we read back."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import holoviews as hv\n",
    "hv.extension('bokeh')\n",
    "import numpy as np\n",
    "ktp = cw.ktp.Basic()\n",
    "key, text = ktp.next()  # manual creation of a key, text pair can be substituted here\n",
    "\n",
    "trace = cw.capture_trace(scope, target, text)\n",
    "hv.Curve(trace.wave).opts(width=600, height=600)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Further Modifications"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You might be able to tell where our loop is happening, but to make sure, let's modify it and see how the trace changes. Change when the loop ends and save the file. Rebuild the file:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bash -s \"$PLATFORM\" \"$CRYPTO_TARGET\"\n",
    "cd ../hardware/victims/firmware/simpleserial-base-lab2\n",
    "make PLATFORM=$1 CRYPTO_TARGET=$2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Reprogram the target:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "cw.program_target(scope, prog, fw_path)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And capture a new trace:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "trace2 = cw.capture_trace(scope, target, text)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "hv.Curve(trace2.wave).opts(width=600, height=600)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "It should now be very obvious where our loop is happening. Verify that the number of similar looking power spikes matches how many times the loop is run. Now let's take a look at how different operations affect power traces:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparing Operations"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To make things easy on us, let's select operations that we would expect to have very different power traces. One easy metric to base your decision on is how long the associated instructions take to execute (which is typically documented either in the datasheet, or in the core's documentation). For example, on XMEGA we'll compare adding (1 cycle) with multiplying (2 cycles)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### XMEGA"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### STM32F3"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Our reference for the STM32F3 (which has an Arm Cortex M4 CPU) will the [Cortex M4 Instruction Set Summary](http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.ddi0439b/CHDDIGAC.html). As we can see, the multiply instruction takes 1 cycle to execute, while the divide instruction takes between 2 and 12. These instructions also have analogous C operations (* and /) so it will be easy to get the compiler to insert them.\n",
    "\n",
    "This is a pretty drastic difference, so the two instructions should look very different. Change your loop so that it preforms multiplications each time through:\n",
    "\n",
    "```C\n",
    "volatile int b = 0xAFFA;\n",
    "for (volatile int i = 0; i < 10; i++)\n",
    "    b *= 11;\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Capture: Operation 1"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now rebuild and capture another trace:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bash -s \"$PLATFORM\" \"$CRYPTO_TARGET\"\n",
    "cd ../hardware/victims/firmware/simpleserial-base-lab2\n",
    "make PLATFORM=$1 CRYPTO_TARGET=$2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "cw.program_target(scope, prog, fw_path)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "trace3 = cw.capture_trace(scope, target, text)\n",
    "hv.Curve(trace3.wave).opts(width=600, height=600)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Capture: Operation 2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Replace your first operation with your second. Save the file, rebuild, program, and capture another trace."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bash -s \"$PLATFORM\" \"$CRYPTO_TARGET\"\n",
    "cd ../hardware/victims/firmware/simpleserial-base-lab2\n",
    "make PLATFORM=$1 CRYPTO_TARGET=$2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "cw.program_target(scope, prog, fw_path)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "trace4 = cw.capture_trace(scope, target, text)\n",
    "hv.Curve(trace4.wave).opts(width=600, height=600)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Compare the traces. Is the one that you expected to be longer actually longer?\n",
    "\n",
    "The longer operation is typically more complicated than the other operation, which means we would expect it to have higher power consumptions as well. Do you also see this behaviour in the traces you captured?"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Disconnecting from ChipWhisperer"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now that we're done with the tutorial, we'll need to disconnect from ChipWhisperer, so that we can connect to it in a different tutorial:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "scope.dis()\n",
    "target.dis()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Conclusion"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In this tutorial you have learned how power analysis can tell you the operations being performed on a microcontroller. In future work we will move towards using this for breaking various forms of security on devices. In particular, Tutorial B3-1 will examine how we can use this information to exploit a password check."
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python",
   "pygments_lexer": "ipython3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
